//
//  StatusDAL.swift
//  Weibo09
//
//  Created by Romeo on 15/9/18.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

private let clearCacheTimeTravel: NSTimeInterval = -60 * 60 * 24 * 7
//private let clearCacheTimeTravel: NSTimeInterval = -60

class StatusDAL: NSObject {
    
    //清理缓存
    class func clearCacheStatus(){
        let date = NSDate(timeIntervalSinceNow: clearCacheTimeTravel)
        let df = NSDateFormatter()
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let str = df.stringFromDate(date)
        let sql = "DELETE FROM T_Status WHERE createTime < '\(str)'"
        SQLiteManager.sharedManager.execSQL(sql)
    }
    
    
    /*
    开发的步骤 :
    1.存储数据
    2.检测本地是否有缓存数据
    */
    
    class func loadStatuses(since_id: Int, max_id: Int,completion: (array: [[String : AnyObject]]?) ->()){
        //1.检测本地是否有缓存数据
        let list = loadCacheStatus(since_id, max_id: max_id)
        //2.如果有缓存数据的话  直接返回缓存数据
        if list?.count ?? 0 > 0 {
            completion(array: list)
            return
        }
        //3.没有缓存数据  去网络加载数据
        NetworkTools.sharedTools.loadStatus(since_id: since_id, max_id: max_id).subscribeNext({ (result) -> Void in
            // 1. 获取 result 中的 statuses 字典数组
            guard let array = result["statuses"] as? [[String: AnyObject]] else {
                printLog("没有正确的数据")
                completion(array: nil)
                return
            }
            print(array)
            //4.立即将网络返回数据  缓存一下
            saveStatus(array)
            //完成网络请求成功的回调
            completion(array: array)
            
            }, error: { (error) -> Void in
                completion(array: nil)
            }) {print("信号完成")}
        
        
    }
    
    class func loadCacheStatus(since_id: Int, max_id: Int) -> [[String : AnyObject]]?{
        // 初始刷新: statuses 数组没有内容
        // 下拉刷新: 取 statuses 的第一项的 id 作为 since_id
        // 上拉刷新: 取 statuses 的最后一项的 id 作为 max_id
        let userId = UserAccountViewModel.sharedUserAccount.userAccount!.uid!
        var sql = "SELECT status FROM T_Status WHERE userId = \(userId)\n"
        if since_id > 0{
            //下拉刷新
            sql += "AND statusId > \(since_id)\n"
        } else if max_id > 0 {
            //上拉加载更多
            sql += "AND statusId < \(max_id)\n"
        }
        sql += "ORDER BY statusId DESC LIMIT 20"
        
        
        //定义一个接收数据的数组
        var result: [[String : AnyObject]]?
        if let list = SQLiteManager.sharedManager.execRecordSet(sql){
            result = [[String : AnyObject]]()
            //将字符串转换为字典
            for item in list {
                let statusString = item["status"] as! String
                let data = statusString.dataUsingEncoding(NSUTF8StringEncoding)!
                let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as! [String : AnyObject]
                result?.append(dict)
            }
        }
        
        return result
    }
    
    class func saveStatus(array: [[String : AnyObject]]){
        
        //引入事务   批量插入
        let manager = SQLiteManager.sharedManager
        //开启事务
        manager.beginTranscation()
        //编写 sql 语句
        let sql = "INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?);"
        //顺序插入数据
        //userId  userAccount'
        let userId = UserAccountViewModel.sharedUserAccount.userAccount!.uid!
        //数据操作结果标记
        var result = true
        for dict in array {
            //1.statusId (status  'id')
            let statusId = dict["id"] as! Int
            //status (dict["statuses"]$0 )
            //2.先讲字典转为字符串
            let data = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(rawValue: 0))
            //将 data 转成字符串
            let statusString = String(data: data, encoding: NSUTF8StringEncoding)!
            
            result = manager.prepareExecSQL(sql, parmas: statusId,statusString,userId)
            if !result {
                break
            }
        }
        if result {
            print("提交事务")
            manager.commitTtansaction()
        } else {
            print("回滚事务")
            manager.rollBackTranscation()
        }
    }
}
